import os.path
import sys

import pub_readconf
import pub_config

import deploy_redis


# 检查要安装的组件是否被占用
def get_deploy_info(deploy_type):
    """
    传入类型
    :param deploy_type: redis,nginx,mysql
    :return:
    """
    # 配置
    deploy_obj = pub_readconf.ReadConf(os.path.join(pub_config.ROOT_PATH, 'conf/deploy.yml'))
    deploy_data = deploy_obj.read_yaml()

    # 根据传入的中间件类型读对应的配置文件
    deploy_type_item = deploy_data[deploy_type]
    # 判断是否集群安装
    if deploy_type_item['cluster']:
        # 返回集群信息字典列表
        redis_cluster_list = []
        # 集群模式保留根路径
        redis_cluster_path = deploy_type_item['redis_path']
        # 以nodes为主，只要redis_path，redis_pwd
        for node in deploy_type_item['nodes']:
            cluster_node = node.split(':')
            cluster_node_dict = {"cluster_ip": cluster_node[0], "cluster_port": cluster_node[1]}
            for item in deploy_data['hosts']:
                # 合并字典
                if cluster_node_dict['cluster_ip'] == item['host_ip']:
                    deploy_type_item['redis_path'] = str(redis_cluster_path+'_'+cluster_node_dict['cluster_port'])
                    redis_cluster_list.append({**cluster_node_dict, **item, **deploy_type_item})
        return redis_cluster_list
    else:
        # 返回单机信息字典
        return {**deploy_data['hosts'][0], **deploy_type_item}


def install_type(deploy_type):
    deploy_type_info = get_deploy_info(deploy_type)
    if deploy_type == 'redis':
        if isinstance(deploy_type_info, list):
            # 集群
            deploy_redis.cluster_install(deploy_type_info)
        else:
            # 单机
            deploy_redis.single_install(deploy_type_info)
    elif deploy_type == 'mysql':
        if isinstance(deploy_type_info, list):
            # 集群
            pass
        else:
            # 单机
            pass
    else:
        print("要部署的类型{}未找到或暂不支持".format(deploy_type))
        sys.exit()


if __name__ == '__main__':
    install_type('redis')
